package org.rc.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.rc.dto.*;
import org.rc.entity.*;
import org.rc.enums.DevType;
import org.rc.service.*;
import org.rc.util.BusinessTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/conversation")
public class ConversationController {

    @Autowired
    SlpService slpService;

    @Autowired
    RoomDevService roomDevService;

    @Autowired
    RoomService roomService;

    @Autowired
    ShspService shspService;

    @Autowired
    ConversationRecordService conversationRecordService;

    @Autowired
    ConversationTextService conversationTextService;

    @Autowired
    UserRoomService userRoomService;

    @Autowired
    UserService userService;

    @Autowired
    MicService micService;

    @Value("${slp.text.endpoint}")
    private String slpTextEndpoint;

    @GetMapping("/begin")
    public Res beginConversation(@RequestParam(value = "mac") String mac){
        log.info("开始谈话，根据mac获取信息--->{}",mac);
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("textEndpoint",slpTextEndpoint);
        //根据mac地址查询房间，再根据房间查询当前使用的用户
        mac = BusinessTool.handleMac(mac);
        Slp slp = slpService.getSlpByMac(mac);
        if(null == slp){
            return Res.failure("当前设备尚未在系统中配置");
        }
        RoomDev roomSlp = roomDevService.getRoomDevByTypeAndDevId(DevType.SLP.getType(),slp.getId());
        if(null ==roomSlp){
            return Res.failure("当前设备尚未绑定房间，无法开启谈话");
        }
        List<RoomDev> roomShsp = roomDevService.getRoomDevByRoomIdAndDevId(DevType.SHSP.getType(),roomSlp.getRoomId());
        if(!CollectionUtils.isEmpty(roomShsp)){
            Shsp shsp = shspService.getByShspId(roomShsp.get(0).getDevId());
            log.info("神火视频地址--->{}",shsp.getRtsp());
            jsonObject.put("rtsp",shsp.getRtsp());
        }
        UserRoom userRoom = userRoomService.getBindRecordByRoomId(roomSlp.getRoomId());
        if(null == userRoom){
            return Res.failure("当前房间尚未绑定用户，无法开启谈话");
        }
        ConversationRecord conversationRecord = new ConversationRecord();
        conversationRecord.setUserId(userRoom.getUserId());
        conversationRecord.setRoomId(userRoom.getRoomId());
        conversationRecord.setBeginTime(LocalDateTime.now());
        conversationRecordService.addRecord(conversationRecord);
        log.info("-----------record---->{}",conversationRecord.getId());
        jsonObject.put("recordId",conversationRecord.getId());
        return Res.success(jsonObject);
    }

    @GetMapping("/end")
    public Res endConversation(@RequestParam(value = "mac") String mac,@RequestParam(value = "recordId") Long recordId){
        log.info("谈话结束，mac--->{},recordId--->{}",mac,recordId);
        ConversationRecord conversationRecord = conversationRecordService.getByConversationId(recordId);
        if(null != conversationRecord){
            conversationRecord.setEndTime(LocalDateTime.now());
            conversationRecordService.end(conversationRecord);
        }
        return Res.success("success");
    }

    @PostMapping("/page")
    public Res getConversationPage(@RequestBody ConversationRecordPageDto conversationRecordPageDto){
        User loginUser = userService.getByUserId(conversationRecordPageDto.getLoginId());
        Long userIdP = conversationRecordPageDto.getUserId();
        if(1!=loginUser.getIsAdmin()){
            userIdP = conversationRecordPageDto.getLoginId();
        }
        long pageNo = conversationRecordPageDto.getPageNo();
        long pageSize = conversationRecordPageDto.getPageSize();
        Long roomIdP = conversationRecordPageDto.getRoomId();
        String beginTime = conversationRecordPageDto.getBeginTime();
        String endTime = conversationRecordPageDto.getEndTime();

        List<ConversationPageRes> conversationPageRes = new ArrayList<>();
        Page<ConversationRecord> conversationRecordPage =  conversationRecordService.getConversationRecordPage(pageNo,pageSize,roomIdP
                ,userIdP,beginTime,endTime);
        List<ConversationRecord> conversationRecords = conversationRecordPage.getRecords();
        Map<Long,User> userMap = new HashMap<>();
        Map<Long,Room> roomMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(conversationRecords)){
            List<Long> userList = conversationRecords.stream().map(ConversationRecord ::getUserId).collect(Collectors.toList());
            List<Long> roomList = conversationRecords.stream().map(ConversationRecord ::getRoomId).collect(Collectors.toList());
            List<User> users = userService.getByUserIds(userList);
            List<Room> rooms = roomService.getByRoomIds(roomList);
            if(!CollectionUtils.isEmpty(users)){
                userMap = users.stream().collect(Collectors.toMap(User :: getId,user -> user));
            }
            if(!CollectionUtils.isEmpty(rooms)){
                roomMap = rooms.stream().collect(Collectors.toMap(Room :: getId,room -> room));
            }
            for(ConversationRecord conversationRecord:conversationRecords){
                ConversationPageRes conversationPageRe = ConversationPageRes.getInstance(conversationRecord);
                long userId = conversationRecord.getUserId();
                long roomId = conversationRecord.getRoomId();
                if(userMap.containsKey(userId)){
                    conversationPageRe.setUserName(userMap.get(userId).getName());
                }
                if(roomMap.containsKey(roomId)){
                    conversationPageRe.setRoomName(roomMap.get(roomId).getName());
                }
                conversationPageRes.add(conversationPageRe);
            }
        }
        PageDto pageDto = PageDto.of(conversationRecordPage);
        pageDto.setData(conversationPageRes);
        return Res.success(pageDto);
    }

    @DeleteMapping("/record/{id}")
    public Res deleteConversation(@PathVariable(value = "id") Long id){
        conversationRecordService.deleteByRecordId(id);
        conversationTextService.deleteByRecordId(id);
        return Res.success();
    }

    @DeleteMapping("/records")
    public Res batchDeleteConversation(@RequestBody ConversationBatchDeleteDto conversationBatchDeleteDto){
        List<Long> ids = conversationBatchDeleteDto.getIds();
        if(CollectionUtils.isEmpty(ids)){
            return Res.failure("请选择需要删除的谈话记录");
        }
        conversationRecordService.deleteByRecordIds(ids);
        conversationTextService.deleteByRecordIds(ids);
        return Res.success();
    }

    @PostMapping("/text/page")
    public Res getTxtByRecords(@RequestBody ConversationTextPageDto conversationTextPageDto){
        return Res.success(PageDto.of(conversationTextService.getRolePage(conversationTextPageDto)));
    }


}
